package com.winchain.chainbill.basic.invoice.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shell.bee.base.annotation.Logging;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.entity.mvc.RetMsg;
import com.shell.bee.file.service.PubFileUploadService;
import com.shell.bee.file.vo.FileWapper;
import com.shell.bee.invoince.service.InvUseStatsService;
import com.shell.bee.mvc.controller.BaseController;
import com.shell.bee.ocr.api.OcrApi;
import com.shell.bee.ocr.invoice.OcrInvoiceReq;
import com.shell.bee.ocr.invoice.OcrInvoiceRes;
import com.shell.bee.persistence.model.PageLimit;
import com.shell.bee.persistence.model.PageModel;
import com.shell.feign.PubUserFeign;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.governor.user.po.PubUser;
import com.winchain.chainbill.basic.charge.service.ValComRecService;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import com.winchain.chainbill.basic.invoice.po.BasInvoice;
import com.winchain.chainbill.basic.invoice.service.BasInvoiceService;
import com.winchain.chainbill.basic.invoice.vo.BasInvoiceVo;
import com.winchain.chainbill.bill.biz.discount.service.BillDctQueryService;
import com.winchain.chainbill.bill.biz.discount.vo.DctForInvoiceVo;

@RestController
public class BasInvoiceController extends BaseController {
	@Autowired
	private BasInvoiceService basInvoiceService;
	@Autowired
	private CusRecService cusRecService;
	@Autowired
	BillDctQueryService billDctQueryService;
	@Autowired
	private PubUserFeign pubUserFeign;
	@Autowired
	private ValComRecService valComRecService;
	@Resource(name = "${file.updownload.service}")
	private PubFileUploadService pubFileUploadService;
	@Autowired
	private InvUseStatsService invUseStatsService;

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "OCR��������������")
	public OcrInvoiceRes resolveVatInvoice(@RequestParam(value = "fileId", required = false) String fileId)
			throws Exception {
		FileWapper fileWapper = this.pubFileUploadService.getDownloadFile(fileId);
		OcrInvoiceReq req = new OcrInvoiceReq();
		req.setImagePath(fileWapper.getFile().getPath());
		OcrInvoiceRes res = OcrApi.vatInvoice(req);
		if (OcrApi.valInvoiceSuccess(res)) {
			String invNo = res.getInvoiceNum();
			String invCode = res.getInvoiceCode();
			BigDecimal balance = this.invUseStatsService.countBalanceByCodesAndNos(new String[] { invCode },
					new String[] { invNo });
			if ((balance == null) && (!StringUtil.emptyAndNull(res.getAmountInFiguers()))) {
				try {
					balance = new BigDecimal(res.getAmountInFiguers());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			res.setInvoiceBalance(balance);
		}
		return res;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "����������������")
	public List<BasInvoice> getBasInvoicesByPage(PageLimit limit, BasInvoiceVo basInvoiceVo) throws Exception {
		basInvoiceVo.setCusId(CommonDataUtil.getCurEntId());
		return this.basInvoiceService.selectBasInvoicesByPage(limit, basInvoiceVo);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������")
	public BigDecimal getInvoiceBalance(String invCode, String invNo) throws Exception {
		BigDecimal balance = this.invUseStatsService.countBalanceByCodesAndNos(new String[] { invCode },
				new String[] { invNo });
		return balance;
	}

	@RequestMapping
	@Logging(module = "������������", methods = "����������������������")
	public List<BasInvoice> getBasInvoicesForMgtByPage(PageLimit limit, BasInvoiceVo basInvoiceVo) throws Exception {
		if ("1".equals(basInvoiceVo.getInvoiceType())) {
			basInvoiceVo.setFinId(CommonDataUtil.getCurEntId());
		}
		return this.basInvoiceService.selectBasInvoicesForMgtByPage(limit, basInvoiceVo);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "����������")
	public RetMsg saveInvoice(BasInvoice basInvoice, String relJson) throws Exception {
		if (this.basInvoiceService.saveInvoice(basInvoice, relJson)) {
			return new RetMsg("success", "������������������������1-3����������");
		}
		return new RetMsg("success", "����������������");
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������������������")
	public Map<String, Object> getAddInitData() {
		Map<String, Object> map = new HashMap();
		CusRec cusRec = (CusRec) this.cusRecService.selectByKey(CommonDataUtil.getCurEntId());
		if (StringUtil.emptyAndNull(cusRec.getCity())) {
			map.put("contactAddr", cusRec.getProvince() + cusRec.getAddress());
		} else {
			map.put("contactAddr", cusRec.getProvince() + cusRec.getCity() + cusRec.getAddress());
		}
		map.put("taxNo", cusRec.getSocCrCode());
		PubUser user = this.pubUserFeign.selectByKey(CommonDataUtil.getUserId());
		map.put("emailAddr", user.getEmail());
		map.put("contactNum", user.getPhoneNo());
		return map;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "����������������������")
	public List<DctForInvoiceVo> getUnApplyBills(PageLimit limit, String dctIds, String finId, String invoiceType)
			throws Exception {
		List<DctForInvoiceVo> list = this.billDctQueryService.selectUnApplyBills(limit, dctIds, finId, invoiceType);
		PageModel<DctForInvoiceVo> pageModel = (PageModel) list;
		if ((list != null) && (list.size() > 0) && ("2".equals(invoiceType))) {
			DctForInvoiceVo invoiceVo = (DctForInvoiceVo) list.get(0);
			String cusId = invoiceVo.getFinId();
			CusRec cusRec = (CusRec) this.cusRecService.selectByKey(cusId);
			String operatorName = this.valComRecService.selectOneByCusIdAndGrpId(cusId, cusRec.getGrpId())
					.getOperatorName();
			pageModel.getExtend().put("operatorName", operatorName);
		}
		return pageModel;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������")
	public Map<String, Object> getInvoiceDetails(String invoiceId) {
		Map<String, Object> map = new HashMap();
		map.put("invoiceForm", this.basInvoiceService.selectByKey(invoiceId));
		map.put("invoiceRels", this.billDctQueryService.selectApplyBills(invoiceId));
		return map;
	}

	@RequestMapping
	@Logging(module = "����������", methods = "��������/��������������")
	public RetMsg pass(String invoiceIds) throws Exception {
		String result = this.basInvoiceService.pass(invoiceIds);
		if (result.equals("success")) {
			return new RetMsg("success", "��������������");
		}
		if (result.equals("done")) {
			return new RetMsg("warning", false, "������������������������");
		}
		if (result.equals("pdone")) {
			return new RetMsg("warning", false, "����������������������������");
		}
		return new RetMsg("error", "��������������");
	}
}
